/**
 * 张志浩(作者)
 * 2018-05-17(开始日期)
 * 2018--(最终更改日期)
 * xxx(最后更改者)
 * */
//var apicom = "http://192.168.30.199:10001/";
/* 再来一单 */
var orderIds = globalFun.GetQueryString("id");
var data = {};
var fwMsg = sessionStorage.getItem("fwMsg");
var fwType = JSON.parse(fwMsg);
if(fwType == 0){
	$("#service_time").removeClass("open-popup");
}
if(orderIds) {
	Auth();
	$.ajax({
		type: "post",
		url: apicom + "mobile/after/order/queryOneceAgainServieOrder",
		data: {
			id: orderIds,
			memberId: user_info.id
		},
		success: function(res) {
			if(typeof res == "string") {
				var res = JSON.parse(res);
			} else {
				var res = res;
			}
			if(res.code == 1) {

				fwData = res.content;
				$("#link_name").val(fwData.linkman)
				$("#link_phone").val(fwData.linkphone)
				//var fwTime = stamp2time(fwData.beginTime, "-", true);
				var fwTime = "选择服务时间"
				if(fwData.endTime) {
					fwTime = stamp2time(fwData.beginTime, "-", false);
					fwTime += "至";
					fwTime = stamp2time(fwData.endTime, "-", false);
				}
				$("#service_time").html(fwTime);
				$(".service_name").html(fwData.title);
				var price = fwData.price * 1;
				price = price.toFixed(2).toString();
				$("#total_price").html(price);
				$(".pay_price i.int").html(price.split(".")[0])
				$(".pay_price i.float").html(price.split(".")[1]);
				if(fwData.type == 1) {
					$(".service_type span").html("到家服务");
					$("#picker").val(fwData.serviceAdd)
					$("#detail_addr input").val(fwData.detailAdd)
				} else {
					$(".service_type span").html("到店服务")
					$(".home_addr").hide()
				}
				//$("#num").html();
				$(".service_cover").css({
					"background-image": "url(" + fwData.imageAddress + ")"
				})
				data.type = fwData.type;
				data.fwId = fwData.serviceId;
				data.price = price;
				var bkTime =  stamp2time(fwData.beginTime, "-", false)
				var bcTime =  stamp2time(fwData.endTime, "-", false)
				data.starttime = bkTime;
				if(fwData.endTime) {
					data.endTime = bcTime
				}
				$("#sure_addr").attr("data-did", fwData.serviceAdd);
				//locationReplace(rootdomain + "html/service/topay.html?t=" + data.createdTime + "&p=" + data.orderMoney + "&v=" + data.orderIds + "&id=" + data.orderId + "&type=1&from=app")
			} else {
				//locationReplace(rootdomain + "html/service/topay.html?err=" + data.msg + "&type=1&from=app")
				tips(res.msg);
			}
		},
		error: function(err) {
			tips("服务器错误!");
		}
	});
} else if(data) {
	getOrderInfo()
}
/* 时间戳转日期时间 */

function stamp2time(timestamp, symbol, showH) { //symbol年月日之间的分隔符，showH是否展示时分秒
	var str = timestamp.toString();
	if(str.length == 10) {
		timestamp *= 1000;
	}
	var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
	Y = date.getFullYear() + symbol;
	M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + symbol;
	D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate() + ' ';
	h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours() + ':';
	m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
	//s = date.getSeconds();
	if(showH) {
		return Y + M + D + h + m;
	}
	return Y + M + D;

}

/* 手机号输入校验 */
$("#link_phone").on("input", function() {
	this.value = this.value.replace(/\D/, "");
})

function getOrderInfo() {
	//data
	data = JSON.parse(fwMsg);
	/*data = {
	  service_type_id: 1,
	  title: "空调安装",
	  image_address: "https://yst-pjyc-server.oss-cn-beijing.aliyuncs.com/datas/image/20180417/20180417102544771770878.jpg",
	  price: "100",
	  service_start_time: 1526562146000,
	  service_end_time: 1526562148000
	}*/
	if(data.type == 1) {
		$(".service_type span").html("到家服务")
	} else {
		$(".service_type span").html("到店服务")
		$(".home_addr").hide()
		//var start = stamp2time(data.service_start_time, "/");
		//var end = stamp2time(data.service_end_time, "/");
		$("#service_time").html(data.starttime + "到" + data.endtime)
	}
	$(".service_name").html(data.title);
	//$("#num").html();
	$(".service_cover").css({
		"background-image": "url(" + data.imgUrl + ")"
	})
	var price = data.price * 1;
	price = price.toFixed(2).toString();
	$("#total_price").html(price);
	$(".pay_price i.int").html(price.split(".")[0])
	$(".pay_price i.float").html(price.split(".")[1])
}

/* 获取三十天内的日期 */
var d = new Date($.ajax({
	async: false
}).getResponseHeader("Date"));
var weekday = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
var year, month, myddy, day, r; //month当前月份，myddy当前星期几，day当前日期
var content = "";
for(var i = 1; i < 31; i++) {
	r = d.getDate();
	day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate(); //获取存储当前日期
	myddy = d.getDay(); //获取存储当前星期
	r < 0 ? month = d.getMonth() < 10 ? '0' + d.getMonth() : d.getMonth() : month = d.getMonth() + 1 < 10 ? '0' + parseInt(d.getMonth() + 1) : d.getMonth() + 1; //获取存储当前月份
	year = d.getFullYear();
	if(i == 1) {
		content += '<li class="nav_active today" data-date="' + year + '-' + month + '-' + day + '" data-id="' + month + '月' + day + '日(今天)"><p>' + "今天" + '</p>';
		content += '<p>' + month + '-' + day + '</p></li>';
	} else if(i == 2) {
		content += '<li  data-date="' + year + '-' + month + '-' + day + '" data-id="' + month + '月' + day + '日(明天)"><p>' + "明天" + '</p>';
		content += '<p>' + month + '-' + day + '</p></li>';
	} else {
		content += '<li  data-date="' + year + '-' + month + '-' + day + '" data-id="' + month + '月' + day + '日(' + weekday[myddy] + ')"><p>' + weekday[myddy] + '</p>';
		content += '<p>' + month + '-' + day + '</p></li>';
	}
	r = d.getDate() + 1; //日期加1
	d.setDate(Math.abs(r)); //重新设置当前时间
}
$("#main_nav").append(content) //回显

/* 时间序列 */
// 今天
function render_today() {
	var hour = d.getHours(); //获取当前小时数(0-23)
	var min = d.getMinutes(); //获取当前分钟数(0-59)
	if(min >= 30) {
		render_time(hour + 1, 0)
	} else {
		render_time(hour, min)
	}
}
render_today()

/* 渲染时间序列 */
function render_time(h, m) {
	var minute = ["00", "30"];
	var time_list = "",
		class_name = "";
	for(var i = 9; i <= 19; i++) {
		if(i < h) {
			class_name = "t_disabled";
		} else {
			class_name = "";
		}
		if(i == 19) {
			time_list += "<li class='" + class_name + "' data-id='" + i + ":" + minute[0] + "'><p>" + i + ":" + minute[0] + "</p></li>"
			break;
		}
		for(var j = 0; j < 2; j++) {

			if(i == h && m > 0 && j == 0) {
				console.log(i + "--" + h + "--" + m + "--" + j)
				class_name = "t_disabled";
			} else if(i == h) {
				class_name = "";
			}
			time_list += "<li class='" + class_name + "' data-id='" + i + ":" + minute[j] + "'><p>" + i + ":" + minute[j] + "</p></li>"
		}
	}
	$("#time_list").html(time_list);
}
/* 时间导航点击事件 */
$("#main_nav").on("click", "li", function() {
	$(this).addClass("nav_active").siblings().removeClass("nav_active");
	if($(this).hasClass("today")) {
		render_today() //今天
	} else {
		render_time(9, 0) //其他天
	}
})
/* 时间序列点击事件 */
$("#time_list").on("click", "li", function() {
	var disabled = $(this).hasClass("t_disabled");
	var active = $(this).hasClass("t_active");
	if(disabled || active) {
		return;
	}
	$(this).addClass("t_active").siblings().removeClass("t_active");
})
$("#sure_time").click(function() {
	var date = $("#main_nav").find(".nav_active").attr("data-date");
	var day = $("#main_nav").find(".nav_active").attr("data-id");
	var h_m = $("#time_list").find(".t_active").attr("data-id");
	if(!(day && h_m)) {
		$.toast("请选择服务时间");
		return
	}
	$("#service_time").html(day + h_m).attr("data-date", date + " " + h_m)
	$.closeModal(".popup-services")
})
/* 点击选择地区弹窗显示 */
Auth();
getCityList("", 0); //页面加载获取省份列表
$("#picker").click(function() {
	$("#addr_wrap").show();
	$("#mask").show();
})
/* 点击选择地区弹窗隐藏 */
$("#mask").click(function() {
	$("#addr_wrap").hide();
	$("#mask").hide();
	$("#picker").val("");
})
/* 省/城市/区县 tab切换 */
$("#city_tab").on("click", "li", function() {
	$(this).addClass('t_active').siblings().removeClass("t_active");
	var id = $(this).attr("data-id");
	$("#" + id).show().siblings(".city_list").hide();
})
/* 选择收货地址-省 */
$("#s_list").on("click", "li", function() {
	var pid = $(this).attr("data-id");
	var val = $(this).find("span").html();
	$(this).parent().hide().next().show();
	$("#c_btn").addClass("t_active").siblings().removeClass("t_active");
	$(this).addClass("selected").siblings().removeClass("selected");
	$("#sure_addr").attr("data-pid", pid);
	$("#sure_addr").attr("data-cid", "");
	$("#sure_addr").attr("data-did", "");
	$("#picker").val(val)
	getCityList(pid, 1)
})
/* 选择收货地址-城市 */
$("#c_list").on("click", "li", function() {
	var cid = $(this).attr("data-id");
	var val = $(this).find("span").html();
	$(this).parent().hide().next().show();
	$("#d_btn").addClass("t_active").siblings().removeClass("t_active");
	$(this).addClass("selected").siblings().removeClass("selected");
	$("#sure_addr").attr("data-cid", cid);
	$("#sure_addr").attr("data-did", "");
	var pname = $("#s_list .selected >span").html()
	val = pname + val;
	$("#picker").val(val);
	getCityList(cid, 2)
})
/* 选择收货地址-区县 */
$("#q_list").on("click", "li", function() {
	var did = $(this).attr("data-id");
	var val = $(this).find("span").html();
	$(this).addClass("selected").siblings().removeClass("selected");
	$("#sure_addr").attr("data-did", did);
	var pname = $("#s_list .selected >span").html()
	var cname = $("#c_list .selected >span").html()
	val = pname + cname + val;
	$("#picker").val(val);
})
/* 确认服务地址 */
$("#sure_addr").click(function() {
	var pid = $("#sure_addr").attr("data-pid");
	var cid = $("#sure_addr").attr("data-cid");
	var did = $("#sure_addr").attr("data-did");
	if(!did) {
		$.toast("请选择服务地址");
		return;
	}
	$.closeModal(".popup-addr")
	$("#addr_temp").attr("data-pid", pid);
	$("#addr_temp").attr("data-cid", cid);
	$("#addr_temp").attr("data-did", did);
})
$(document).on("click", ".popup-overlay", function() {
	console.log(111)
	$.closeModal(".popup-addr");
})
/* 获取城市列表 */
function getCityList(id, type) {
	if(type == 2) {
		$el = $("#q_list")
	} else if(type == 1) {
		$el = $("#c_list")
	} else {
		$el = $("#s_list")
	}
	$.ajax({
		url: apicom + "mobile/after/memberaddress/getPositionList",
		type: "post",
		data: {
			uuid: user_info.uuid,
			phone: user_info.phone,
			type: type,
			id: id
		},
		success: function(res) {
			if(typeof(res) == 'string') {
				res = JSON.parse(res);
			}
			var data = res.content;
			var conStr = "";
			if(res.code == 1) {
				for(var i = 0; i < data.length; i++) {
					conStr += '<li data-id="' + data[i].id + '"><span>' + data[i].name + '</span></li>';
				}
				$el.html(conStr);
			} else {
				$.toast(res.msg);
			}
		}
	})
}
/* 提交订单 */
$("#sub_order").click(function() {
		submitOrder(this)
})
function submitOrder(self) {
	//console.log(this)
	//var topicId
	//var shareMemberId
	var did = $("#sure_addr").attr("data-did");
	var detail_addr = $("#detail_addr input").val();
	var link_name = $("#link_name").val();
	var link_phone = $("#link_phone").val();
	var service_time = $("#service_time").html();
	if(link_name !== "0" && link_name == false) {
		tips("请填写联系人");
		return;
	}
	if(link_phone == false) {
		tips("请填写联系人手机号");
		return;
	}
	if(link_phone < 11) {
		tips("联系人手机号错误");
		return;
	}
	if(data.type == 1 && !detail_addr) {
		tips("请填写详细地址");
		return;
	}
	if(data.type == 1 && !did) {
		tips("请选择收货地址");
		return;
	}
	if(data.type == 1 && service_time == "选择服务时间") {
		tips("请选择服务时间");
		return;
	}
	if($(self).hasClass("disabled")) {
		return;
	}
	if(Auth()) {
		$(self).addClass("disabled");
		var dataObj = {
			uuid: user_info.uuid,
			phone: user_info.phone,
			id: user_info.id,
			serviceId: data.fwId,
			num: 1,
			linkman: link_name,
			linkphone: link_phone
		}
		switch(mark) {
			case 0:
				dataObj.orderSource = 2;
				break;
			case 1:
				dataObj.orderSource = 1;
				break;
			default:
				dataObj.orderSource = 3;
		}
		if(data.type == 1) {
			dataObj.beginTime = $("#service_time").attr("data-date")
			dataObj.serviceAdd = $("#picker").val()
			dataObj.detailAdd = detail_addr
		} else {
			dataObj.beginTime = data.starttime;
			dataObj.endTime = data.endtime;
		}
		if(data.topicId) {
			dataObj.topicId = data.topicId;
		}
		if(data.shareMemberId && data.shareMemberId != "null") {
			dataObj.shareMemberId = data.shareMemberId;
		}
		console.log(dataObj)
		$.ajax({
			type: "post",
			url: apicom + "mobile/after/order/createServieOrder",
			data: dataObj,
			async: false,
			dataType: "json",
			success: function(res) {
				if(typeof(res) == 'string') {
					res = JSON.parse(res);
				}
				setTimeout(function() {
					$(self).removeClass("disabled");
				}, 2000)
				if(res.code == 1) {
					var createdTime = res.content.createdTime;
					var v = res.content.orderIds;
					//if (res.content.payType == 2) {
					//locationReplace(rootdomain + "html/service/complete.html?v=" + v + "&oId=" + res.content.id)
					//} else {
					if(orderIds){
						window.location.href = rootdomain + "html/service/topay.html?t=" + createdTime + "&p=" + data.price + "&v=" + v + "&id=" + res.content.id + "&type=1"
					}else{
						locationReplace(rootdomain + "html/service/topay.html?t=" + createdTime + "&p=" + data.price + "&v=" + v + "&id=" + res.content.id + "&type=1")
					}

					//}
					//window.location.replace(rootdomain + "html/service/topay.html?t=" + createdTime + "&p=" + data.price + "&v=" + v + "&id=" + res.content.id + "&type=1");
				} else {
					tips(res.msg);
				}
			},
			error: function(err) {
				$(self).removeClass("disabled");
				console.log(err)
			}
		})
	} else {
		sessionStorage.setItem('history', window.location.href);
		toClientLogin(location.href)
	}
}
/* 替换当前页面url */
function locationReplace(url) {
	if(history.replaceState) {
		history.replaceState(null, document.title, url);
		history.go(0);
	} else {
		location.replace(url);
	}
}
/* 返回 */
$("#go_back").click(function() {
	var from_app = globalFun.GetQueryString("from");
	if(from_app && from_app == "app") {
		// console.log(1111)
		if($(self).hasClass("disabled")) {
			return false
		}
		$(self).addClass("disabled")
		setTimeout(function() {
			$(self).removeClass("disabled")
		}, 1000)
		if(mark == 0) {
			window.stub.goBack();
		} else if(mark == 1) {
			setupWebViewJavascriptBridge(function(bridge) {
				bridge.callHandler('goBack', function(resp) {});
			})
		}
	} else {
		window.history.go(-1)
	}
})
/* 路由功能 */
$.config = {
	// 路由功能开关过滤器，返回 false 表示当前点击链接不使用路由
	routerFilter: function($link) {
		// 某个区域的 a 链接不想使用路由功能
		if($link.is('.disable-router a')) {
			return false;
		}
		return true;
	}
};

$.init();